package com.project.service.server;

import java.io.*;

/**
 * 处理响应信息
 */
public class Response {
    private OutputStream out;
    public Response(OutputStream out){
        this.out = out;
    }

    /**
     * 发送文本数据到客户端
     * @param info 文本数据
     */
    public void sendMessage(String info){
        try {
            out.write(info.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送文件数据到客户端
     * @param filePath 文件路径
     */
    public void sendFile(String filePath){
        File file = new File(filePath);
        //文件不存在时，跳出方法
        if(file.exists() == false){
            return;
        }

        InputStream in  = null;
        try {
            //建立服务器本地文件读取流
            in = new FileInputStream(file);

            byte[] by = new byte[1024];
            int len = 0;
            //将读取流数据读取到字节数组，返回当前读取的字节数
            while( (len = in.read(by)) != -1){
                out.write(by,0,len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
